package com.hk.core.autoconfigure.data.database;

import com.hk.commons.util.StringUtils;
import com.hk.core.authentication.api.SecurityContextUtils;
import com.hk.core.autoconfigure.data.TenantIdResolverProvider;
import com.hk.core.jdbc.tenants.TenantIdResolver;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Objects;

/**
 * @author Kevin
 * @date 2024-04-11 22:59
 */
@RequiredArgsConstructor
public final class UserPrincipalTenantIdResolver implements TenantIdResolver {

    private final List<TenantIdResolverProvider> resolverProviders;

    @Override
    public String resolve(String value) {
        if (Objects.nonNull(resolverProviders) && SecurityContextUtils.isAuthenticated()) {
            var principal = SecurityContextUtils.getPrincipal();
            for (var resolverProvider : resolverProviders) {
                if (resolverProvider.test(value)) {
                    var result = resolverProvider.getProvider().apply(principal);
                    if (StringUtils.hasLength(result)) {
                        return result;
                    }
                }
            }
        }
        return null;
    }
}
